package com.itheima52.mobilesafe.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itheima52.mobilesafe.R;
import com.itheima52.mobilesafe.utils.StreamUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class SplashActivity extends Activity {
	protected static final int CODE_UPDATE_DIALOG = 0;
	protected static final int CODE_URL_ERROR = 1;
	protected static final int CODE_NET_ERROR = 2;
	protected static final int CODE_JSON_ERROR = 3;
	protected static final int CODE_ENTER_HOME = 4;// 进入主页面
	private TextView tvVersion;
	private String mVersionName;// 版本名
	private int mVersionCode;// 版本号
	private String mDesc;// 版本描述
	private String mDownloadUrl;// 版本url
	private TextView tvProgress;// 下载进度展示

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {// msg.what有默认值为0.
			case CODE_UPDATE_DIALOG:
				showUpdateDailog();
				break;
			case CODE_URL_ERROR:
				Toast.makeText(SplashActivity.this, "url错误", 0).show();
				enterHome();
				break;
			case CODE_NET_ERROR:
				Toast.makeText(SplashActivity.this, "net错误", 0).show();
				// download();
				showUpdateDailog();
				// enterHome();
				break;
			case CODE_JSON_ERROR:
				Toast.makeText(SplashActivity.this, "json错误", 0).show();
				enterHome();
				break;
			case CODE_ENTER_HOME:
				enterHome();
				break;

			default:
				break;
			}

		};
	};
	private SharedPreferences mPref;
	private RelativeLayout rlRoot;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		tvVersion = (TextView) findViewById(R.id.tv_version);
		tvVersion.setText("版本号:" + getVersionName());
		tvProgress = (TextView) findViewById(R.id.tv_progress);// 默认隐藏
		rlRoot = (RelativeLayout) findViewById(R.id.rl_root);

		mPref = getSharedPreferences("config", MODE_PRIVATE);

		copyDB("address.db");// 拷贝归属地查询数据库

		

		// 判断是否需要自动更新
		boolean autoUpdate = mPref.getBoolean("auto_update", true);
		if (autoUpdate) {
			checkVersion();
		} else {
			// 延时2秒钟发一条消息
			mHandler.sendEmptyMessageDelayed(CODE_ENTER_HOME, 2000);
		}

		// 让闪屏页面有个渐变动画效果,0.3透明到完全透明
		AlphaAnimation anim = new AlphaAnimation(0.3f, 1f);
		anim.setDuration(5000);
		rlRoot.startAnimation(anim);
		// 创建快捷方式
				createShortcut();

	}

	/**
	 * 创建快捷方式
	 */
	private void createShortcut() {

		Intent intent = new Intent();
		/**
		 * 1干什么事情 2叫什么名字 3长什么样子
		 * 
		 */
		intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
		intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, BitmapFactory
				.decodeResource(getResources(), R.drawable.home_apps));
		intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "黑马手机卫士");
		intent.putExtra("duplicate", false);
		// 不能使用显示意图,要使用影视意图
		Intent shortcut_intent = new Intent();
		shortcut_intent.setAction("qidongshouye");
		shortcut_intent.addCategory("android.intent.category.DEFAULT");

		intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcut_intent);
		sendBroadcast(intent);

	}

	/**
	 * 返回版本名
	 * 
	 * @return
	 */
	private String getVersionName() {
		PackageManager packageManager = getPackageManager();
		try {
			// 获取包的信息
			PackageInfo packageInfo = packageManager.getPackageInfo(
					getPackageName(), 0);
			int versionCode = packageInfo.versionCode;
			String versionName = packageInfo.versionName;
			System.out.println("versionCode:" + versionCode + ",versionName:"
					+ versionName);
			return versionName;

		} catch (NameNotFoundException e) {
			// 没有找到包名会走此异常
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 返回版本号
	 * 
	 * @return
	 */
	private int getVersionCode() {
		PackageManager packageManager = getPackageManager();
		try {
			// 获取包的信息
			PackageInfo packageInfo = packageManager.getPackageInfo(
					getPackageName(), 0);
			int versionCode = packageInfo.versionCode;
			return versionCode;

		} catch (NameNotFoundException e) {
			// 没有找到包名会走此异常
			e.printStackTrace();
		}
		return -1;

	}

	/**
	 * 从服务器获取版本信息进行校验
	 * 
	 */
	private void checkVersion() {
		final long startTime = System.currentTimeMillis();
		// 启动子线程异步加载
		new Thread() {

			public void run() {

				Message msg = Message.obtain();
				HttpURLConnection conn = null;
				try {
					URL url = new URL("http://10.0.2.15:8080/update.json");
					conn = (HttpURLConnection) url.openConnection();
					conn.setRequestMethod("GET");// 设置请求方法
					conn.setConnectTimeout(5000);// 设置请求超时
					conn.setReadTimeout(5000);// 设置响应超时,连接上了,服务器迟迟不给响应
					conn.connect();// 连接服务器
					int responseCode = conn.getResponseCode();// 获取响应码
					if (responseCode == 200) {// 正常情况
						InputStream inputStream = conn.getInputStream();
						String result = StreamUtils.readFromStream(inputStream);
						System.out.println("网络结果返回:" + result);
						// 解析json
						JSONObject jo = new JSONObject(result);
						mVersionName = jo.getString("versionName");
						mVersionCode = jo.getInt("versionCode");
						mDesc = jo.getString("description");
						mDownloadUrl = jo.getString("downloadUrl");
						if (mVersionCode > getVersionCode()) {// 判断是否有更新
							// 服务器的版本号>本地的版本号
							// 说明有更新,弹出升级对话框
							msg.what = CODE_UPDATE_DIALOG;

						} else {
							// 没有版本更新
							msg.what = CODE_ENTER_HOME;
						}
					}
				} catch (MalformedURLException e) {
					// URL异常
					msg.what = CODE_URL_ERROR;
					e.printStackTrace();
				} catch (IOException e) {
					// 网络错误异常
					msg.what = CODE_NET_ERROR;
					e.printStackTrace();
				} catch (JSONException e) {
					// json解析失败
					msg.what = CODE_JSON_ERROR;
					e.printStackTrace();
				} finally {
					long endTime = System.currentTimeMillis();
					long timeUsed = endTime - startTime;// 访问网络花费的时间
					if (timeUsed < 5000) {
						// 强制休眠一段时间,保证闪屏页展示5秒钟
						try {
							Thread.sleep(5000 - timeUsed);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					mHandler.sendMessage(msg);
					if (conn != null) {
						// 关闭网络连接
						conn.disconnect();
					}
				}

			};
		}.start();
	}

	/**
	 * 弹出升级对话框
	 */
	protected void showUpdateDailog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				SplashActivity.this);
		builder.setTitle("最新版本:" + mVersionName);
		builder.setMessage(mDesc);
		// builder.setCancelable(false); 用户体验差
		builder.setPositiveButton("立即更新", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// 下载apk
				download();

			}
		});
		builder.setNegativeButton("以后再说", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// 跳到主页面
				enterHome();

			}
		});
		// 设置对话框取消的监听,用户点击返回键时触发
		builder.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				// 跳到主界面
				enterHome();

			}
		});
		builder.show();// show()方法中有create()方法.

	}

	/**
	 * 下载apk文件
	 */
	protected void download() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			tvProgress.setVisibility(View.VISIBLE);// 显示进度

			String target = Environment.getExternalStorageDirectory()
					+ "/update.apk";
			// XUtils
			HttpUtils utils = new HttpUtils();

			utils.download(
					"http://msoftdl.360.cn/mobilesafe/shouji360/360safesis/360MobileSafe_6.3.1.1054.apk",
					target, new RequestCallBack<File>() {
						// 下载成功
						@Override
						public void onSuccess(ResponseInfo<File> arg0) {
							Toast.makeText(SplashActivity.this, "下载成功!", 0)
									.show();
							// 跳转到安装页面
							Intent intent = new Intent(Intent.ACTION_VIEW);
							intent.addCategory(Intent.CATEGORY_DEFAULT);
							// 要导入org.apache.http.legacy.jar
							intent.setDataAndType(Uri.fromFile(arg0.result),
									"application/vnd.android.package-archive");
							// startActivity(intent);
							startActivityForResult(intent, 0);// 如果用户取消安装的话,会得到取消结果

						}

						// 文件下载进度,该方法在主线程运行
						@Override
						public void onLoading(long total, long current,
								boolean isUploading) {
							super.onLoading(total, current, isUploading);
							System.out.println("下载进度:" + current + "/" + total);
							tvProgress.setText("下载进度:" + current * 100 / total
									+ "%");
						}

						// 下载失败
						@Override
						public void onFailure(HttpException arg0, String arg1) {
							Toast.makeText(SplashActivity.this, "不好意思,下载失败!", 0)
									.show();

						}
					});
		} else {
			Toast.makeText(SplashActivity.this, "没有sd卡", 0).show();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 取消安装进入主界面
		enterHome();
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 进入主页面
	 */
	private void enterHome() {
		Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
		startActivity(intent);
		finish();// 关闭闪屏页
	}

	/**
	 * 拷贝数据库
	 */
	private void copyDB(String dbName) {
		File filesDir = getFilesDir();
		// 路径:/data/data/com.itheima52.mobilesafe/files
		System.out.println("路径:" + filesDir);
		File destFile = new File(getFilesDir(), dbName);// 文件的路径:文件夹+文件名
		if (destFile.exists()) {
			System.out.println("数据库" + dbName + "已经存在");
			return;
		}

		FileOutputStream out = null;
		InputStream in = null;
		try {
			in = getAssets().open(dbName);
			out = new FileOutputStream(destFile);
			int len = 0;
			byte[] buffer = new byte[1024];
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

}
